const Ws = require('ws')

;((Ws)=>{
    const server = new Ws.Server({port:8888});
    const init = ()=>{
        bindEvent();
    }
    function bindEvent(){
        server.on('open',function(){
            console.log('服务器启动了');
        })
        server.on('close',handleClose)
        server.on('error',handleError)
        server.on('connection',handleConnection)
    }
    function handleClose(){
        console.log('服务器关闭了');
    }
    function handleError(){
        console.log('服务器出错了');
    }
    function handleConnection(ws){
        console.log('服务器连接了');
        ws.on('message',handleMessage)
    }
    //广播事件
    function handleMessage(msg){
        server.clients.forEach((c)=>{
            c.send(msg.toString())
        })
        console.log(JSON.parse( msg.toString()));
    }
    init();
})(Ws);